package pack1;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.*;

import swim.sessionbeans.UserManagerRemote;

/**
 * Servlet implementation class RegistrationServlet
 */
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public String firstname;
	public String lastname;
	public String username;
	public String md5password;
	public String mail;
	public String picturename;
	public String pictureest;
	public String pictureurl;

    /**
     * Default constructor. 
     */
    public RegistrationServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Creazione nuovo utente");
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {			
			List<FileItem> fields = upload.parseRequest(request);			
			Iterator<FileItem> it = fields.iterator();
			if (!it.hasNext()) {
				return;
			}
			while (it.hasNext()) {				
				FileItem fileItem = it.next();
				boolean isFormField = fileItem.isFormField();
				if (!isFormField) {
					try{
					//System.out.println("NON SONO UN FORM FIELD");
						picturename = fileItem.getName();										
						pictureest = picturename.substring(picturename.lastIndexOf("."));					
						picturename = username+"_picture_"+Long.toString(System.currentTimeMillis())+pictureest;									
						String root = getServletContext().getRealPath("/");
					
						File path = new File(root + "/users_pictures");
						if(!path.exists()){
							path.mkdirs();
						}
					
						File uploadedFile = new File(path + "/" + picturename);
					
						fileItem.write(uploadedFile);						
						pictureurl = "./users_pictures/"+picturename;
					}catch (Exception e){
						e.printStackTrace();
						pictureurl = "./users_pictures/default.png";
					}											  
					System.out.println("IMMAGINE SALVATA: "+pictureurl);
				}else{							
					//System.out.println("SONO UN FORM FIELD");
					String fieldName = fileItem.getFieldName();					
						if(fieldName.equals("firstname")){ 
							firstname = fileItem.getString();
						}else if(fieldName.equals("lastname")){
							lastname = fileItem.getString();							
						}else if(fieldName.equals("username")){
							username = fileItem.getString();
						}else if(fieldName.equals("password")){
							String password = fileItem.getString();
							MessageDigest md = MessageDigest.getInstance("MD5"); //START MD5 conversion
							md.update(password.getBytes(),0,password.length());  //..
							md5password = new BigInteger(1,md.digest()).toString(16); // password in md5 in md5password
						}else if(fieldName.equals("mail")){
							mail = fileItem.getString();							
						}
				}
			}
			InitialContext jndiContext = new InitialContext();
			UserManagerRemote man = (UserManagerRemote) jndiContext.lookup("UserManager/remote");
			//System.out.println("VARIABILI: "+firstname+" - "+lastname+" - "+username+" - "+md5password+" - "+mail);
			man.addNewUser(username, md5password, mail, firstname, lastname, pictureurl);			
			request.getSession().setAttribute("pageMessage", "Congratulations "+username+" you're now registered to SWIMv2!");
			request.getSession().setAttribute("pageMessageType", "success");
			response.sendRedirect("./");
		} catch (Exception e) {
			request.getSession().setAttribute("pageMessage", "Something was wrong with your registration, try again please!");
			request.getSession().setAttribute("pageMessageType", "error");
			response.sendRedirect("./");
			e.printStackTrace();
		}
	}

}
